
package net.sea.commons.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * XML工具类
 *
 * @author huachengwu 
 */
public class XMLUtils {
	/**
	 * 根据xml文件获取document对象
	 * 
	 * @param file
	 *            xml文件
	 * @return document对象
	 * @throws DocumentException
	 */
	public static Document getDocument(File file) throws DocumentException {
		SAXReader reader = new SAXReader();
		return reader.read(file);
	}

	/**
	 * 根据xml字符串获取document对象
	 * 
	 * @param xmlStr
	 *            xml字符串
	 * @return document对象
	 * @throws DocumentException
	 */
	public static Document getDocument(String xmlStr) throws DocumentException {
		return DocumentHelper.parseText(xmlStr);
	}

	/**
	 * 获取节点的属性映射
	 * 
	 * @param e
	 *            xml节点
	 * @return 节点的属性映射
	 */
	public static Map<String, String> getAttributes(Element e) {
		Map<String, String> map = new HashMap<String, String>();
		if (e != null) {
			for (Iterator<?> it = e.attributeIterator(); it.hasNext();) {
				Attribute attribute = (Attribute) it.next();
				map.put(attribute.getName(), attribute.getText());
			}
		}
		return map;
	}

	/**
	 * 获取节点的所有子节点
	 * 
	 * @param e
	 *            xml节点
	 * @return 节点的所有子节点
	 */
	public static List<Element> getChildren(Element e) {
		List<Element> list = new ArrayList<Element>();
		if (e != null) {
			for (Iterator<?> it = e.elementIterator(); it.hasNext();) {
				list.add((Element) it.next());
			}
		}
		return list;
	}

	/**
	 * 
	 * @param doc
	 *            DOM文档对象
	 * @param xmlFile
	 *            xml文件
	 * @throws IOException
	 */
	public static void wirteXML(Document doc, File xmlFile) {
		// 输出全部原始数据，在编译器中显示
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");// 根据需要设置编码
		// 输出全部原始数据，并用它生成新的我们需要的XML文件
		XMLWriter writer = null;
		try {
			writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(
					xmlFile), "UTF-8"), format);
			writer.write(doc); // 输出到文件
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("XML文件写入错误");
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
					writer = null;
					throw new RuntimeException("写入流关闭异常");
				}
			}
		}

	}
}

/*
 * 修改历史 $Log$
 */